package com.tbit.uqbike.service.business.tag.event;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Sets;
import com.tbit.uqbike.enums.CancelType;
import com.tbit.uqbike.enums.UserType;
import com.tbit.uqbike.service.business.machine.event.MachineDeleteEvent;
import com.tbit.uqbike.service.business.tag.TagBindService;
import com.tbit.uqbike.webmanager.dto.TagBindDTO;
import com.tbit.uqbike.webmanager.dto.TagDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 标签删除成功事件监听器
 *
 *
 * @author <a href="mailto:chen.chaoxiong@tbit.com.cn">ChenChaoXiong</a>
 * @since 2024/7/15
 */
@Component
@Slf4j
public class TagEventListener {

    @Autowired
    private TagBindService tagBindService;

    @EventListener
    public void onTagDeleteSuccess(TagDeleteSuccessEvent event) {
        log.info("TagEventListener.onTagDeleteSuccess {}", JSON.toJSONString(event));
        TagDTO tag = event.getTag();
        TagBindDTO tagBindDTO = new TagBindDTO();
        tagBindDTO.setTagIds(Sets.newHashSet(tag.getId()));
        tagBindDTO.setUserInfo(tag.getUserInfo());
        tagBindDTO.setCancelType(CancelType.DELETE_TAG);
        tagBindDTO.setUserType(UserType.MANAGER);
        tagBindService.cancelByTagId(tagBindDTO);
    }

    @EventListener
    public void onTagDisableSuccess(TagDisableSuccessEvent event) {
        log.info("TagEventListener.onTagDisableSuccess {}", JSON.toJSONString(event));
        //禁用标签时，不取消标签绑定
        return;
//        TagDTO tag = event.getTag();
//        TagBindDTO tagBindDTO = new TagBindDTO();
//        tagBindDTO.setTagIds(Sets.newHashSet(tag.getId()));
//        tagBindDTO.setUserInfo(tag.getUserInfo());
//        tagBindDTO.setCancelType(CancelType.DISABLE_TAG);
//        tagBindDTO.setUserType(UserType.MANAGER);
//        tagBindService.cancelByTagId(tagBindDTO);
    }

    @EventListener
    public void  onMachineDelete(MachineDeleteEvent event) {
        log.info("TagEventListener.onMachineDelete {}", JSON.toJSONString(event));
        List<Integer> machineIds = event.getMachineIds();
        if (CollectionUtil.isNotEmpty(machineIds)) {
            tagBindService.deleteByMachineId(machineIds);
        }

    }
}